use axum::{
    extract::Request,
    http::{HeaderValue, StatusCode},
    middleware::Next,
    response::{IntoResponse, Redirect, Response},
};
use tower_cookies::Cookies;

use crate::{STATIC_PREFIX, TOKEN_NAME};

pub async fn handle_charset(request: Request, next: Next) -> Result<Response, StatusCode> {
    let path = request.uri().path().to_string();
    let mut response = next.run(request).await;
    let header = response.headers_mut();
    if path.starts_with(STATIC_PREFIX) {
        //静态资源目录下的html响应，修改编码为utf-8
        header.append(
            "Content-Type",
            HeaderValue::from_str("text/html;charset=utf-8").unwrap(),
        );
    }
    return Ok(response);
}

pub async fn auth(cookies: Cookies, request: Request, next: Next) -> Result<Response, StatusCode> {
    let path = request.uri().path().to_string();
    let method = request.method().to_string();
    //允许访问的路径,:POST 表示是post请求
    let unauth = vec![
        "/",
        "/index",
        "/search",
        "/topic/get",
        "/topic/pass",
        "/reply:POST",
        "/login",
        "/sitemap",
    ];
    let ignore = unauth
        .into_iter()
        .filter(|f| {
            let mut split = f.split(":").into_iter();
            let p = split.next().unwrap_or_default();
            let m = split.next();
            path.eq(p) && m.map_or(true, |f| f.eq(method.as_str()))
        })
        .count()
        > 0;
    let login = cookies.get(TOKEN_NAME).map_or(false, |_| true);
    if login || ignore || path.starts_with(STATIC_PREFIX) {
        let response = next.run(request).await;
        return Ok(response);
    }
    let path = request
        .uri()
        .path_and_query()
        .map_or(None, |f| Some(f.as_str()))
        .unwrap_or_default();
    let response = Redirect::to(format!("/login?redirect={}", path).as_str()).into_response();
    Ok(response)
}
